<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								发货单
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="发货状态" prop="shipmentStatusId">
							<el-input class="my" readonly type="text" v-model="formData.shipmentStatusId" clearable>
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${shipmentStatusIndex===key?'#fff':''};${shipmentStatusIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in shipmentStatusTags" :key="key"
											:checked="shipmentStatusIndex===key"
											@change="tagChange(key,'shipmentStatusId')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="客户" prop="customer">
									<el-select @clear="selectClear('customer')" v-model="formData.customer"
										@change="(value:any)=>selectChange(value,'customer')" multiple ref="customer"
										clearable>
										<el-option v-for="item in customerOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="customerOption[customerIndex]?.color">
															<component :is="customerOption[customerIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{customerOption[customerIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="销售订单" prop="salesOrder">
									<el-select @clear="selectClear('salesOrder')" v-model="formData.salesOrder"
										@change="(value:any)=>selectChange(value,'salesOrder')" multiple
										ref="salesOrder" clearable>
										<el-option v-for="item in salesOrderOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="salesOrderOption[salesOrderIndex]?.color">
															<component :is="salesOrderOption[salesOrderIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{salesOrderOption[salesOrderIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="formData.shipmentStatusId===123 ? 12 : 0">
								<el-form-item label="出库单" prop="outboundOrder">
									<el-input type="text" v-model="formData.outboundOrder" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="formData.shipmentStatusId===123 ? 12 : 24">
								<el-form-item label="申请发货日期" prop="applyDeliveryDate">
									<el-date-picker style="width:100%;" v-model="formData.applyDeliveryDate"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16" v-show="!formData.shipmentStatusId || formData.shipmentStatusId!==120">
							<el-col :span="12">
								<el-form-item label="申请人" prop="applicant">
									<el-input placeholder="请填写" type="text" v-model="formData.applicant"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请日期" prop="applyDate">
									<el-date-picker placeholder="请选择" v-model="formData.applyDate" style="width:100%;"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<div class="static-content-item">
							<div>收货信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="收货人" prop="consignee">
									<el-input placeholder="请填写" type="text" v-model="formData.consignee"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="收货电话" prop="consigneePhone">
									<el-input placeholder="请填写" type="text" v-model="formData.consigneePhone" clearable>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="收货地址" prop="consigneeAddress">
							<el-input type="text" clearable v-model="formData.consigneeAddress">
								<template #prefix>
									<el-button size="small" text :icon="Position" @click="geolocations">
									</el-button>
									<el-icon class="is-loading" v-if="formData.loading">
										<svg class="circular" viewBox="-10, -10, 50, 50">
											<path class="path" d="
										            M 30 15
										            L 28 17
										            M 25.61 25.61
										            A 15 15, 0, 0, 1, 15 30
										            A 15 15, 0, 1, 1, 27.99 7.5
										            L 15 15
										          " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)" />
										</svg>
									</el-icon>
								</template>
							</el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>发货信息</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="发货方式" prop="shippingMethod">
									<el-input class="my" type="text" readonly v-model="formData.shippingMethod"
										clearable>
										<template #prefix>
											<div>
												<el-check-tag
													:style="`color: ${shippingMethodIndex===key?'#fff':''};${shippingMethodIndex===key?`background: ${item.bg}`:''}`"
													v-for="(item,key) in shippingMethodTags" :key="key"
													:checked="shippingMethodIndex===key"
													@change="tagChange(key,'shippingMethod')">{{item.text}}</el-check-tag>
											</div>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="发货人" prop="deliverer">
									<el-input placeholder="请填写" type="text" v-model="formData.deliverer" clearable>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item v-show="formData.shippingMethod >0&& formData.shippingMethod ===127" label="车牌号"
							prop="licensePlate">
							<el-input type="text" v-model="formData.licensePlate" clearable>
							</el-input>
						</el-form-item>
						<el-form-item v-show="formData.shippingMethod >0&& formData.shippingMethod===128" label="快递单号"
							prop="trackinNumber">
							<el-input type="text" v-model="formData.trackinNumber" clearable>
							</el-input>
						</el-form-item>
						<el-form-item label="实际出库日期" prop="actualOutboundDate">
							<el-date-picker placeholder="请选择" v-model="formData.actualOutboundDate" style="width:100%;"
								type="date" />
						</el-form-item>
						<el-form-item>
							<el-input type="text" ref="salesPerson" readonly clearable class="my1">
								<template #prefix>
									<div style="margin: 0;padding: 0;">
										<el-tabs v-model="activeName" @tab-click="handleClick" class="my">
											<el-tab-pane label="发货明细" name="order">
												<div class="flex-space-between"
													style="height: 48px;padding-left: 10px;">
													<el-text type="info" size="small">
														来自 <el-text type="primary" size="small">发货明细</el-text> 的数据
														共{{formData.tableData.length}}条
													</el-text>
													<el-text>
														<el-tooltip effect="light" :hide-after="50" content="创建"
															placement="top">
															<div class="my-a" @click="setTableData">
																<el-icon size="16px" color="#409EFF">
																	<CirclePlus />
																</el-icon>
															</div>
														</el-tooltip>
													</el-text>
												</div>
												<!--  -->
												<el-scrollbar style="width: calc(100vw - 48px - 32px);height: 300px;">
													<el-table @cell-dblclick="tableCellClick" v-loading="loading"
														:data="formData.tableData" :stripe="false" table-layout="auto"
														:default-sort="{}" border style="width: 100%;height: 300px;"
														class="my">
														<el-table-column width="76" fixed="left" prop="id"
															:sortable="false">
															<template #default="scope">
																<el-tooltip effect="light" :hide-after="50" content="复制"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="copyTableData(scope.$index)"
																		:icon="DocumentAdd"></el-button>
																</el-tooltip>
																<el-tooltip effect="light" :hide-after="50" content="删除"
																	placement="top">
																	<el-button style="padding: 0;" class="my"
																		@click="deleteTableData(scope.$index)"
																		:icon="Delete"></el-button>
																</el-tooltip>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="orderDetailId"
															label="所属订单明细*(可选)" :sortable="false">
															<template #default="scope">
																<div class="flex-align-center"
																	v-if="scope.row?.orderDetailId">
																	<el-icon
																		:color="scope.row?.orderDetail?.color || '#82b51b'">
																		<component
																			:is="scope.row?.orderDetail?.icon || CopyDocument">
																		</component>
																	</el-icon>
																	<el-text size="small" style="margin-left: 6px;">
																		{{scope.row?.orderDetail?.label || `${scope.row?.orderDetail?.salesOrder?.orderNumber}_${scope.row.product?.productName + scope.row.product?.model}`}}
																	</el-text>
																</div>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="quantityOrdered" label="下单数量"
															:sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.quantityOrdered || scope.row?.orderDetail?.quantityOrdered}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="pendingShipmentQuantity"
															label="待申请发货数量" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.pendingShipmentQuantity || scope.row?.orderDetail?.pendingShipmentQuantity}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="shippedQuantity"
															label="已发货数量" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.shippedQuantity || scope.row?.orderDetail?.shippedQuantity}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="returnedQuantity"
															label="已退货数量" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.returnedQuantity || scope.row?.orderDetail?.returnedQuantity}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="productId" label="发货产品*(可选)"
															:sortable="false">
															<template #default="scope">
																<div class="flex-align-center"
																	v-show="scope.row.productId">
																	<el-icon
																		:color="productOption.filter(item=>item?.value == scope.row.productId)[0]?.color">
																		<component
																			:is="productOption.filter(item=>item?.value == scope.row.productId)[0]?.icon">
																		</component>
																	</el-icon>
																	<el-text size="small"
																		style="margin-left: 6px;">{{productOption.filter(item=>item?.value == scope.row.productId)[0]?.label}}</el-text>
																</div>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="unitId" label="单位"
															:sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.products?.d2Label || scope.row?.product?.unitId}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="currentInventory"
															label="当前库存数量" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row?.products?.currentInventory || scope.row?.product?.currentInventory}}</el-text>
															</template>
														</el-table-column>
														<el-table-column width="140" prop="quantityShipped"
															label="本次发货数量*(可选)" :sortable="false">
															<template #default="scope">
																<el-text>{{scope.row.quantityShipped}}</el-text>
															</template>
														</el-table-column>
													</el-table>
												</el-scrollbar>
											</el-tab-pane>
										</el-tabs>
									</div>
								</template>
							</el-input>
						</el-form-item>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<!--  -->
			<levitation ref="levitationRef" :option="selectCell.option" :types="types" :st_type="selectCell.type"
				:params="levitationParams" :observerElement="scrollbarRef" :element="element" @change="levitationChange"
				@blur="levitationBlur" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { ElLoading, ElMessage, FormInstance } from 'element-plus';
	import { onMounted, reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {Position, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, UploadFilled, CopyDocument } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber, splitBy } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);
	const activeName = ref('order');
	//levitation start
	const element = ref(null);
	const levitationRef = ref(null);
	const scrollbarRef = ref(null);
	const types = ref('');
	const selectCell = ref({
		id: 0,
		property: '',
		type: '',
		option: []
	});
	const levitationParams = ref(null);
	//levitation end
	// 表单
	const formData = ref({
		shipmentStatusId: null, //发货状态
		customer: [],
		customerId: null, //客户
		salesOrder: [],
		salesOrderId: null, //销售订单
		outboundOrder: [],
		outboundOrderId: null, //出库单
		applyDeliveryDate: '', //申请发货日期
		applicant: '', //申请人
		applyDate: '', //申请日期
		consignee: '', //收货人
		consigneePhone: '', //收货电话
		consigneeAddress: '',//收货地址
		shippingMethod: '',//发货方式
		deliverer: '',//发货人
		licensePlate: '', //车牌号
		trackinNumber: '', //快递单号
		actualOutboundDate: '', //实际出库日期
		customerReceiptProof: '', //客户签收凭证
		customerReceiptDate: '', //客户签收日期
		tableData: [],
		loading: false,
	});
	//验证
	const rules = reactive({
		shipmentStatusId: [{ required: true, message: '发货状态必填！', trigger: ['blur', 'change'] }], //发货状态
		customer: [{ required: true, message: '客户必填！', trigger: ['blur', 'change'] }], //客户
		salesOrder: [{ required: true, message: '销售订单必填！', trigger: ['blur', 'change'] }], //销售订单
		outboundOrderId: [{ required: true, message: '发货状态必选！', trigger: ['blur', 'change'] }], //出库单
		applyDeliveryDate: [{ required: true, message: '申请发货日期必填！', trigger: ['blur', 'change'] }], //申请发货日期
		applicant: [], //申请人
		applyDate: [], //申请日期
		consignee: [{ required: true, message: '收货人必填！', trigger: ['blur', 'change'] }], //收货人
		consigneePhone: [{ required: true, message: '收货电话必填！', trigger: ['blur', 'change'] }], //收货电话
		consigneeAddress: [{ required: true, message: '收货地址必填！', trigger: ['blur', 'change'] }],//收货地址
		shippingMethod: [{ required: true, message: '发货方式必选！', trigger: ['blur', 'change'] }],//发货方式
		deliverer: [{ required: true, message: '发货人必填！', trigger: ['blur', 'change'] }],//发货人
		licensePlate: [], //车牌号
		trackinNumber: [], //快递单号
		actualOutboundDate: [{ required: true, message: '实际出库日期必选！', trigger: ['blur', 'change'] }], //实际出库日期
		customerReceiptProof: [], //客户签收凭证
		customerReceiptDate: [{ required: true, message: '客户签收日期必选！', trigger: ['blur', 'change'] }], //客户签收日期
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//发货状态
	const shipmentStatusTags = ref([]);
	const shipmentStatusIndex = ref(-1);
	//客户选项
	const customerOption = ref([]);
	const customerIndex = ref(-1);
	const customer = ref(null);
	//销售订单
	const salesOrderOption = ref([]);
	const salesOrderIndex = ref(-1);
	const salesOrder = ref(null);
	//发货方式
	const shippingMethodTags = ref([]);
	const shippingMethodIndex = ref(-1);
	//商品
	const productOption = ref([]);
	//订单明细
	const orderDetailOption = ref([]);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getShipmentList();
				getCustomerList();
				getShippingList();
				getOrderDetailListAll();
				getProductList();
				if (!route.query.id) {
					shipmentStatusIndex.value = 0;
					formData.value.shipmentStatusId = 120;
				}
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		const result = await request({
			url: '/login/selectDeliveryOrderById',
			params: {
				id: route.query.id
			},
		});
		console.log('selectDeliveryOrderById --->', result);
		formData.value = { ...result.data.t };
		//
		formData.value.tableData = [...result.data.t.shipmentDetails];
		//
		return true;
	}
	//设置一个
	const setTableData = () => {
		formData.value.tableData.push({
			id: +new Date(),
			productId: null,
			unitId: null,
			currentInventory: null,
			quantityShipped: null,
			orderDetailId: null,
			quantityOrdered: null,
			pendingShipmentQuantity: null,
			shippedQuantity: null,
			returnedQuantity: null,
			products: null,
			orderDetail: null,
		});
	}
	//复制一个
	const copyTableData = (index : number) => {
		//...
		const item = { ...formData.value.tableData[index] };
		item.id = +new Date();
		formData.value.tableData.push(item);
	}
	//删除一个
	const deleteTableData = (index : number) => {
		formData.value.tableData.splice(index, 1);
	}
	const selectClear = (type : string) => {
		formData.value[type] = [];
	}
	const tableCellClick = (row : any, column : any, cell : HTMLTableCellElement, event : Event) => {
		if (route.query.id) {
			return;
		}
		types.value = '';
		//所属订单明细
		if (column.property === 'orderDetailId') {
			types.value = 'select-icon';
			selectCell.value.option = [...orderDetailOption.value];
		}
		//发货产品
		if (column.property === 'productId') {
			types.value = 'select-icon';
			selectCell.value.option = [...productOption.value];
		}
		//本次发货数量
		if (column.property === 'quantityShipped') {
			types.value = 'number';
		}
		//
		element.value = cell;
		//
		selectCell.value.id = row.id;
		selectCell.value.property = column.property;
		//
		levitationParams.value = row[column.property];
		setTimeout(() => {
			levitationRef.value.getElementInfo();
		}, 1);
		//
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'customer', //哪一个下拉框，根据ref
			option: customerOption, //下拉列表选项
			indexVar: customerIndex, //当前选中项
			idVar: 'customerId', //当前id值
			blurRef: customer, //ref
			fun: getOrderList,
		}, {
			type: 'salesOrder', //哪一个下拉框，根据ref
			option: salesOrderOption, //下拉列表选项
			indexVar: salesOrderIndex, //当前选中项
			idVar: 'salesOrderId', //当前id值
			blurRef: salesOrder, //ref
			fun: getOrderDetailList
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		// if (type === 'shipmentStatusId') {
		// 	if (shipmentStatusIndex.value === index) {
		// 		formData.value[type] = null;
		// 		shipmentStatusIndex.value = -1;
		// 		return;
		// 	}
		// 	shipmentStatusIndex.value = index;
		// 	formData.value[type] = shipmentStatusTags.value[index].value;
		// }
		if (type === 'shippingMethod') {
			if (shippingMethodIndex.value === index) {
				formData.value[type] = null;
				shippingMethodIndex.value = -1;
				return;
			}
			shippingMethodIndex.value = index;
			formData.value[type] = shippingMethodTags.value[index].value;
		}
	}
	//获取发货状态
	const getShipmentList = async () => {
		const data = await getShipments('shipment_status', 'tag');
		//
		console.log('getShipmentList --->', data);
		shipmentStatusTags.value = [];
		data.forEach((item : any, key : number) => {
			shipmentStatusTags.value.push({
				text: item.text,
				bg: item.bg,
				value: item.value
			});
			//
			if (formData.value.shipmentStatusId === item.value) {
				shipmentStatusIndex.value = key;
			}
		});
	}
	//获取客户信息
	const getCustomerList = async () => {
		customerOption.value = [];
		const result = await request({
			url: '/login/selectCustomerAll',
			params: pageData.value,
		});
		//
		console.log('getCustomerList --->', result);
		//
		pageData.value = mergeObjects(pageData.value, result.data.t);
		//
		result.data.t.list.forEach((item : any, key : number) => {
			customerOption.value.push({
				label: `${item.customerName}（${item.customerRating}）${item.billingMethod}`,
				value: item.customerId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.customerId === item.customerId) {
				formData.value.customer = [item.customerId];
				customerIndex.value = key;
				//
				getOrderList(item.customerId);
			}
		});
		//
	};
	//根据id获取订单信息
	const getOrderList = async (id : number) => {
		salesOrderOption.value = [];
		const result = await request({
			url: '/login/selectSaleOrderByCustomerId',
			params: {
				id
			}
		});
		//
		console.log('getOrderList --->', result);
		result.data.t.forEach((item : any, key : number) => {
			salesOrderOption.value.push({
				label: `${item.orderNumber}_${formatNumber(item.orderTotalAmount, '元')}_${item.status} | ${item.customer.customerName}`,
				value: item.orderId,
				icon: WalletFilled,
				color: '#82b51b'
			});
			if (formData.value.salesOrderId === item.orderId) {
				formData.value.salesOrder = [item.orderId];
				salesOrderIndex.value = key;
				//
				getOrderDetailList(item.orderId);
			}
		});
	}
	//获取所有订单明细
	const getOrderDetailListAll = async () => {
		const result = await request({
			url: '/login/selectOrderDetailAll',
			params: pageData.value,
		});
		//
		console.log('getOrderDetailListAll --->', result);
		orderDetailOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			orderDetailOption.value.push({
				label: `${item.salesOrder.orderNumber}_${item.products.productName + item.products.model}`,
				value: item.orderDetailId,
				icon: CopyDocument,
				color: '#82b51b'
			});
		});
	}
	//根据id获取订单明细
	const getOrderDetailList = async (id : number) => {
		const result = await request({
			url: '/login/selectOrderDetailByOrderId',
			params: { id },
		});
		//
		console.log('getOrderDetailList --->', result);
		orderDetailOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			orderDetailOption.value.push({
				label: `${item.salesOrder.orderNumber}_${item.products.productName + item.products.model}`,
				value: item.orderDetailId,
				icon: CopyDocument,
				color: '#82b51b'
			});
		});
	}
	//获取发货方式
	const getShippingList = async () => {
		const data = await getShipments('shipping_method', 'tag');
		//
		console.log('getShippingList --->', data);
		shippingMethodTags.value = [];
		data.forEach((item : any, key : number) => {
			shippingMethodTags.value.push({
				text: item.text,
				bg: item.bg,
				value: item.value
			});
			//
			if (formData.value.shippingMethod === item.value) {
				shippingMethodIndex.value = key;
			}
		});
	}
	//获取所有产品
	const getProductList = async () => {
		const result = await request({
			url: '/login/selectProductAll',
		});
		//
		console.log('getProductList --->', result);
		//
		productOption.value = [];
		result.data.t.forEach((item : any) => {
			productOption.value.push({
				label: `${item?.productName}${item?.model} | 在库${item?.currentInventory}件`,
				value: item?.productId,
				icon: UploadFilled,
				color: '#5283ff'
			});
		})
	}
	//根据id获取订单明细
	const getOrderDetil = async (id ?: string | number, key ?: number) => {
		if (!id) {
			return;
		}
		const result = await request({
			url: '/login/selectOrderDetail',
			params: {
				id
			}
		});
		//
		console.log('getOrderDetil --->', result);
		formData.value.tableData[key] = mergeObjects(formData.value.tableData[key], result.data.t);
		formData.value.tableData[key].orderDetail = {
			label: `${result.data.t.salesOrder.orderNumber}_${result.data.t.products.productName + result.data.t.products.model}`,
			value: result.data.t.orderDetailId,
			icon: CopyDocument,
			color: '#82b51b'
		};
	}

	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value, shipmentDetails: [...formData.value.tableData] };
				delete data.customer;
				delete data.outboundOrder;
				delete data.salesOrder;
				let type = '';
				if (!route.query.id) {
					type = '/saveDeliveryOrder';
				} else {
					type = '/updateDeliveryOrder';
				}
				//
				const result = await request({
					url: '/login' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//失去焦点 ***** 重要！重要！重要！
	const levitationBlur = () => {
		element.value = null;
	}
	//内容改变
	const levitationChange = (value : string | number) => {
		console.log('value --->', value);
		formData.value.tableData.forEach((item : any, key : number) => {
			console.log('item.id --->', item.id, 'selectCell.value.id --->', selectCell.value.id);
			if (item.id === selectCell.value.id) {
				item[selectCell.value.property] = value;
				if (selectCell.value.property === 'orderDetailId') {
					getOrderDetil(value, key);
				}
				// if (selectCell.value.property === 'productId') {
				// 	getProduct(value, key);
				// }
			}
		});
	}
	//滚动
	const handleScroll = (e : any) => {
		// console.log('handleScroll --->', e);
		if (element.value === null) return;
		levitationRef.value.getElementInfo();
	}
	//获取位置
	const geolocations = async () => {
		formData.value.loading = true;
		const { coords: { latitude, longitude } } = await geolocation();
		//
		const result = await request({
			url: 'http://localhost:3000/api/ip/getIpInfoPlus',
			params: { latitude, longitude }
		});
		console.log('geolocations --->', result);
		const { ad_info, address_reference: { town } } = result.data.result;
		const location = `${ad_info.nation}-${ad_info.province}-${ad_info.city} ${ad_info.district}${town.title}${town._dir_desc}`;
		// if (formData.value.location) {
		console.log('location --->', location);
		formData.value.consigneeAddress = location;
		formData.value.loading = false;
		// }
	}
	//获取经纬度信息
	const geolocation = () : Promise<any> => {
		return new Promise((resolve, reject) => {
			navigator.geolocation.getCurrentPosition(
				(result) => {
					console.log('result--->', result);
					resolve(result);
				},
				(error) => {
					switch (error.code) {
						// 处理错误
					}
					reject(error);
				},
				{
					timeout: 5000,
				}
			);
		});
	}
	//
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';
</style>
<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>